const si = require('systeminformation')
const os = require('os')
const { handleError, ErrorTypes } = require('../common/error-handler')

// 添加全局系统信息变量
let globalSystemInfo = null
let lastUpdateTime = 0
const UPDATE_INTERVAL = 500 // 更新间隔改为500ms，提高实时性

// 初始化系统信息
async function initSystemInfo() {
  try {
    // 获取基本系统信息
    const [cpu, mem, disk, osInfo] = await Promise.all([
      si.cpu(),
      si.mem(),
      si.diskLayout(),
      si.osInfo()
    ])
    
    globalSystemInfo = {
      cpu,
      mem,
      disk,
      os: osInfo,
      lastUpdate: Date.now()
    }
    
    return globalSystemInfo
  } catch (error) {
    handleError('初始化系统信息失败', ErrorTypes.SYSTEM, { error })
    return null
  }
}

// 获取系统信息
async function getSystemInfo() {
  try {
    const now = Date.now()
    
    // 如果距离上次更新时间不足间隔时间，返回缓存的数据
    if (now - lastUpdateTime < UPDATE_INTERVAL && globalSystemInfo) {
      return globalSystemInfo
    }
    
    lastUpdateTime = now
    
    // 初始化返回对象
    const result = {
      cpuUsage: '0%',
      cpuTemp: '0°C',
      cpuFreq: '0GHz',
      cpuPlatform: process.platform,
      cpuModel: os.cpus()[0]?.model || '未知',

      memoryUsage: '0%',
      memoryDetails: {
        used: '0GB / 0GB',
        appUsage: '0MB'
      },

      uptime: '0小时0分钟',

      diskUsage: '0%',
      diskDetails: {
        used: '0GB / 0GB',
        available: '0GB可用',
        type: '未知',
        model: '未知',
        physical: '未知'
      },

      initSystemInfo: globalSystemInfo,
      topMemoryProcesses: []
    }
    
    // 并行获取所有系统信息，添加超时处理
    const timeout = 2000 // 2秒超时
    const getData = async (promise) => {
      return Promise.race([
        promise,
        new Promise((_, reject) => 
          setTimeout(() => reject(new Error('获取数据超时')), timeout)
        )
      ])
    }

    const [cpuLoad, cpuTemp, memInfo, fsSize, diskLayout, processes] = await Promise.all([
      getData(si.currentLoad()),
      getData(si.cpuTemperature()),
      getData(si.mem()),
      getData(si.fsSize()),
      getData(si.diskLayout()),
      getData(si.processes())
    ].map(p => p.catch(() => null)))
    
    // 更新CPU信息 - 添加错误处理和默认值
    if (cpuLoad && typeof cpuLoad.currentLoad === 'number') {
      result.cpuUsage = `${Math.min(100, Math.max(0, cpuLoad.currentLoad)).toFixed(1)}%`
    }

    if (cpuTemp && typeof cpuTemp.main === 'number') {
      result.cpuTemp = `${Math.min(100, Math.max(0, cpuTemp.main)).toFixed(1)}°C`
    }

    if (globalSystemInfo?.cpu) {
      result.cpuFreq = `${globalSystemInfo.cpu.speed || 0}GHz`
      result.cpuModel = globalSystemInfo.cpu.brand || globalSystemInfo.cpu.manufacturer || os.cpus()[0]?.model || '未知'
    }

    // 更新内存信息 - 添加错误处理和数据验证
    if (memInfo && memInfo.total > 0) {
      const usedPercent = Math.min(100, Math.max(0, (memInfo.used / memInfo.total) * 100))
      result.memoryUsage = `${usedPercent.toFixed(1)}%`
      
      const usedGB = Math.max(0, memInfo.used / 1024 / 1024 / 1024).toFixed(1)
      const totalGB = Math.max(0, memInfo.total / 1024 / 1024 / 1024).toFixed(1)
      result.memoryDetails.used = `${usedGB}GB / ${totalGB}GB`
      
      const appMemUsage = process.memoryUsage()
      const appMemUsedMB = Math.max(0, appMemUsage.heapUsed / 1024 / 1024).toFixed(1)
      result.memoryDetails.appUsage = `${appMemUsedMB}MB`
    }

    // 更新系统运行时间
    const uptimeSeconds = os.uptime()
    const uptimeHours = Math.floor(uptimeSeconds / 3600)
    const uptimeMinutes = Math.floor((uptimeSeconds % 3600) / 60)
    result.uptime = `${uptimeHours}小时${uptimeMinutes}分钟`

    // 更新磁盘信息 - 添加错误处理和数据验证
    if (fsSize && fsSize.length > 0) {
      const sysDisk = fsSize.find(disk => disk.mount === '/' || disk.mount === 'C:') || fsSize[0]
      
      if (sysDisk && sysDisk.size > 0) {
        const usePercent = Math.min(100, Math.max(0, sysDisk.use))
        result.diskUsage = `${usePercent.toFixed(1)}%`
        
        const usedGB = Math.max(0, sysDisk.used / 1024 / 1024 / 1024).toFixed(1)
        const sizeGB = Math.max(0, sysDisk.size / 1024 / 1024 / 1024).toFixed(1)
        result.diskDetails.used = `${usedGB}GB / ${sizeGB}GB`
        
        const availableGB = Math.max(0, sysDisk.available / 1024 / 1024 / 1024).toFixed(1)
        result.diskDetails.available = `${availableGB}GB可用`
      }
    }
    
    if (diskLayout && diskLayout.length > 0) {
      const sysDiskInfo = diskLayout[0]
      
      if (sysDiskInfo) {
        result.diskDetails.type = sysDiskInfo.type || '未知'
        result.diskDetails.model = sysDiskInfo.name || '未知'
        result.diskDetails.physical = sysDiskInfo.interfaceType || '未知'
      }
    }
    
    // 更新进程信息
    if (processes && processes.list) {
      result.topMemoryProcesses = processes.list
        .sort((a, b) => b.memRss - a.memRss)
        .slice(0, 5)
        .map(proc => ({
          name: proc.name,
          memoryUsage: (proc.memRss / 1024 / 1024).toFixed(1) + 'MB',
          cpu: proc.cpu.toFixed(1) + '%'
        }))
    }
    
    // 更新全局系统信息
    globalSystemInfo = {
      ...globalSystemInfo,
      ...result,
      lastUpdate: now
    }
    
    return result
  } catch (error) {
    handleError('获取系统信息失败', ErrorTypes.SYSTEM, { error })
    return globalSystemInfo || {
      error: '获取系统信息失败',
      message: error.message
    }
  }
}

module.exports = {
  initSystemInfo,
  getSystemInfo,
  // 导出全局系统信息变量，以便其他模块可以访问
  get globalSystemInfo() {
    return globalSystemInfo
  }
}